package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
)

var (
	mux = http.NewServeMux()
)

func StartManager() error {
	listener, err := net.Listen("tcp", fmt.Sprintf(":%d", config.Listen))
	if err != nil {
		return err
	}
	log.Printf("manager is listing on :%d", config.Listen)
	mux.HandleFunc("/api/reload", func(writer http.ResponseWriter, request *http.Request) {
		writer.WriteHeader(200)
		err := ReloadProxy()
		if err != nil {
			_, _ = writer.Write([]byte("failed"))
		} else {
			_, _ = writer.Write([]byte("success"))
		}
	})
	mux.HandleFunc("/api/stop", func(writer http.ResponseWriter, request *http.Request) {
		err := StopProxy()
		writer.WriteHeader(200)
		if err != nil {
			_, _ = writer.Write([]byte("failed"))
		} else {
			_, _ = writer.Write([]byte("success"))
		}
	})
	mux.HandleFunc("/api/start", func(writer http.ResponseWriter, request *http.Request) {
		writer.WriteHeader(200)
		err := StartProxy()
		if err != nil {
			_, _ = writer.Write([]byte("failed"))
		} else {
			_, _ = writer.Write([]byte("success"))
		}
	})
	mux.HandleFunc("/api/reloadJSON", func(writer http.ResponseWriter, request *http.Request) {
		writer.WriteHeader(200)
		bs, err := ioutil.ReadAll(request.Body)
		if err != nil {
			_, _ = writer.Write([]byte("read json failed"))
			return
		}
		err = StopProxy()
		if err != nil {
			_, _ = writer.Write([]byte("stop proxy failed"))
			return
		}
		err = config.LoadJson(bs)
		if err != nil {
			_, _ = writer.Write([]byte("load json failed"))
			return
		}
		err = StartProxy()
		if err != nil {
			_, _ = writer.Write([]byte("start proxy failed"))
		} else {
			_, _ = writer.Write([]byte("success"))
		}
	})

	go http.Serve(listener, mux)

	return nil
}
